//
//  HSMessageController.swift
//  HomeSchoolDemo
//
//  Created by rimi on 16/9/26.
//  Copyright © 2016年 赖虹宇. All rights reserved.
//

import UIKit

class HSMessageController: HSBasicController {
    //消息列表视图模型
    let messageListVM = HSMessListViewModel()
   
    //输入工具栏 
    var inputToolBarV : UIView!
    //文本输入框
    var inputTextF : UITextField!
    //记录键盘状态
    var isKeyBoardShow = false
    
    //记录当前点击按钮对应的cell
    var currentCell = HSMessageCell()
    
    override func viewDidLoad() {
        super.viewDidLoad()
    //注册原形cell
        tableView.register(UINib(nibName: "HSMessageCell", bundle: nil), forCellReuseIdentifier: "messageCell") //xib必须注册原形cell
        //设置预估高度
        tableView.estimatedRowHeight = 200
      
        //如果实现了自定义行高，下面证据代码就不需要
        // tableView.rowHeight = UITableViewAutomaticDimension

        //刷新控件
        tableView.addSubview(refreshC)
        //设置监听
        refreshC.addTarget(self, action: #selector(loadData), for: .valueChanged)
        //添加右边添加消息按钮
        let rightBtn = UIBarButtonItem(imageName: "release_msg_nor", bgImageName: "release_msg_press", target: self, action: #selector(rightBtnClicked))
        navigationItem.rightBarButtonItem = rightBtn
        //加载数据
        loadData()
        
        //添加输入工具条
        inputTextView()
        
    }
    
    //右边按钮回调事件
    @objc fileprivate func rightBtnClicked(){
        let releaseV = HSReleaseInfoController()
         releaseV.hidesBottomBarWhenPushed = true  //隐藏标签栏
        navigationController?.pushViewController(releaseV, animated: true)
      
    }
    
    //加载数据
    override func loadData(){
        //开始刷新
        refreshC.beginRefreshing()
        //获得刷新类型
        let loType = isPull ? LoadType.pull : LoadType.drop
        //请求数据
        messageListVM.requestMessage(loadType: loType) { [weak self](err, isReafresh) in
            //关闭刷新控件
            self?.refreshC.endRefreshing()
            //记录刷新
            self?.isPull = false
            //判断是否刷新视图
            if err != nil{
                return
            }
            if isReafresh {
                //刷新视图
                self?.tableView.reloadData()
            }
        }
    }
    
}

extension HSMessageController{

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messageListVM.messages.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath) as! HSMessageCell
        //设置cell 的选中模式
        cell.selectionStyle = .none
        //获得对应的视图模型
        let messageVM = messageListVM.messages[indexPath.row]
        //传递模型给cell
        cell.messageVM = messageVM
        //获得按钮的回调闭包
        //点赞按钮回调事件
        cell.likeBtnCallBack = { [weak self] (clickCell) -> () in
            
            self?.likeBtnClicked(cell: clickCell as! HSMessageCell)
        }
        //回复按钮回调事件
        cell.replayBtnCallBack = {[weak self] (clickCell) -> () in
           //功能代码块方法
           self?.replayBtnClicked(cell: clickCell as! HSMessageCell)
        }
        return cell
    }
    //cell高度
    //实现下面这个方法，就必须取消下面这个设置
    //tableView.rowHeight = UITableViewAutomaticDimension
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        //获得对应的模型视图
        let messageVM = messageListVM.messages[indexPath.row]
        //返回计算好的高度
        return messageVM.cellHeight
    }
    
}
/// MARK - 点赞回复相关功能
extension HSMessageController{
   //点赞按钮回调方法
    fileprivate func likeBtnClicked(cell : HSMessageCell){
        //获取网络接口地址
        let url = "ZH-schoolname-S-submitJXLike"
        //设置参数
        guard let key = userInfo["key"] else {
            return
        }
        let messageVM = currentCell.messageVM
        let id = messageVM?.message.not_id ?? 0
        let parame = ["key":key,"id":id,"user_type":2]
        HSNetwordTools.shared.downloadData(urlStr: url, parameters: parame) { [weak self] (data, error) in
            print(data)
            guard let data = data as? NSDictionary else{
                HSAlertView.bottomAlertView("网络异常，请检查网络连接")
                return
            }
            switch data["result"] as! Int{
            case 0 :
                //获取返回的数组
                let likeArray = data["data"] as! [[String:Any]]
                //创建一个可变数组
                var modelArray = [HSReplayListModel]()
                for dict in likeArray {
                    let likeModel = HSReplayListModel(dict: dict)
                    modelArray.append(likeModel)
                }
                //将新的模型数组赋值给视图模型中的模型属性
                let message = messageVM?.message
                message?.replaylist = modelArray
                messageVM?.message = message!
                //刷新视图
                self?.tableView.reloadData()
                //刷新指定行
                ////                let indexPath = self.tableView.indexPath(for: self.currentCell)
            //                self.tableView.reloadRows(at: [indexPath!], with: .automatic)
            case 1 :
                HSAlertView.bottomAlertView("点赞失败")
            default :
                break
            }
        }
        
    }
    
    
    
    
    
    
    ///输入框视图
    func inputTextView(){
        //背景视图
        inputToolBarV = UIView(frame: CGRect(x: 0, y: 300, width: screenW, height: 44))
        inputToolBarV.backgroundColor = UIColor().colorWithHex(0xf0f0f0)
        inputToolBarV.isHidden = true
        //添加一个输入框
        inputTextF = UITextField(frame: CGRect(x: 8, y: 0, width: screenW - 66, height: 44))
        
        inputTextF.placeholder = "我用双手帮你成就梦想"
        inputTextF.borderStyle = .roundedRect //圆角
        inputTextF.clearButtonMode = .always
        inputTextF.font = UIFont.systemFont(ofSize: 15)
        inputTextF.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        inputToolBarV.addSubview(inputTextF)
        //添加一个按钮
        let sureBtn = UIButton(type: .custom)
        sureBtn.frame = CGRect(x: screenW - 58, y: 0, width: 50, height: 44)
        sureBtn.setTitle("确定", for: .normal)
        sureBtn.setTitleColor(#colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1), for: .normal)
        sureBtn.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        sureBtn.addTarget(self, action: #selector(sureBtnClicked), for: .touchUpInside)
        inputToolBarV.addSubview(sureBtn)
       //添加输入工具栏到窗口视图
        let kWindow = UIApplication.shared.keyWindow
        kWindow?.addSubview(inputToolBarV)
       
    }
    ///确定按钮的回调方法
   @objc fileprivate func sureBtnClicked(){
    //退出键盘
    inputTextF.resignFirstResponder()
       //获取输入内容
    let inputText = inputTextF.text!
    if  inputText == ""  {
        HSAlertView.bottomAlertView("输入内容不能为空")
        return
    }
    //获得接口地址
    let url = "ZH-schoolname-S-submitJXReplay"
    //获得参数
    //用户key
    let key = userInfo["key"] ?? 0
    //通知id
    let messageVM = currentCell.messageVM
    let not_id = messageVM?.message.not_id ?? 0
    
    //回复人类型
    //设置参数字典 ---默认为2 家长端
    let parame = ["key":key,"id":not_id,"content":inputText,"user_type":2]
    
    //请求数据
    HSNetwordTools.shared.downloadData(urlStr: url, parameters: parame) {[weak self] (data, error) in
        print(data)
        guard let data = data as? NSDictionary else{
            HSAlertView.bottomAlertView("网络异常，请检查网络连接")
            return
        }
        switch data["result"] as! Int{
        case 0 :
            //获取网络数组
            let listArray = data["data"] as! [[String:Any]]
            var modelArray = [HSReplayListModel]()
            for dict in listArray{
                let listModel = HSReplayListModel(dict: dict)
                modelArray.append(listModel)
            }
            //将新的模型数组赋值给视图模型中的模型属性
            let message = messageVM?.message
            message?.replaylist = modelArray
            messageVM?.message = message!
            //刷新视图
            self?.tableView.reloadData()
            //刷新指定行
            ////                let indexPath = self.tableView.indexPath(for: self.currentCell)
        //                self.tableView.reloadRows(at: [indexPath!], with: .automatic)
        case 1:
            HSAlertView.bottomAlertView("数据发送异常")
        default :
            break
        }
    }
    }
    
    /// 回复按钮的点击回调
    func replayBtnClicked(cell : HSMessageCell) {
        //用于记录点击的是否为同一个回复按钮
        let cellEqual = currentCell == cell
        //记录当前cell
        currentCell = cell
        //获得设置输入框为第一响应者，触发键盘自动弹出,然后判断,如果是第一响应者则取消
        if inputTextF.isFirstResponder {
            if cellEqual {
                inputTextF.resignFirstResponder()
            }
        }else{
            inputTextF.becomeFirstResponder()
        }
    }
    //键盘监听的回调方法
    func notificationWithKeyboard(notifiy:NSNotification){
        inputToolBarV.isHidden = false
        //获得键盘的Y值
        let keyBoardRect = notifiy.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue
        let keyBoardY = keyBoardRect?.cgRectValue.minY ?? 0
        print(keyBoardY)
        //取反
        isKeyBoardShow = keyBoardY < screenH ? true : false
        
        //设置输入框视图的Y值
        let toolBarY = isKeyBoardShow ? (keyBoardY - 44) : (keyBoardY + 44)
        inputToolBarV.frame.origin.y = toolBarY
        
        //适配表格视图高度跟随键盘高度
        //先获得当前窗口
        let kWindow = UIApplication.shared.keyWindow
        //获得cell参照于窗口的frame
        let cellframe = kWindow?.convert(currentCell.frame, from: tableView)
        //获得cell的最大Y值
        let cellMaxY = cellframe?.maxY ?? 0
        //计算表格视图的偏移量
        let offSetY = cellMaxY - toolBarY
        if offSetY > 0 {
            //获得表格视图偏移量
            let currentOffset = tableView.contentOffset.y
            //重新设置偏移量改变及动画
            tableView.setContentOffset(CGPoint(x: 0, y: offSetY + currentOffset), animated: true)
        }
    }
    
    //滚动退出编辑事件
    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        inputTextF.resignFirstResponder()
    }
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    override func viewWillAppear(_ animated: Bool) {
        //注册监听键盘弹出的通知
        NotificationCenter.default.addObserver(self, selector: #selector(notificationWithKeyboard(notifiy:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
}
